import puppeteer from 'puppeteer'
// import puppeteer from 'puppeteer-extra'
// import StealthPlugin from 'puppeteer-extra-plugin-stealth'
// puppeteer.use(StealthPlugin())
import { sleep } from '../../util.js'

export default class DB {
  constructor(ctx) {
    this.ctx = ctx
    this.init()
  }

  async init() {
    this.read = true

    const browser = await puppeteer.launch({
      userDataDir: 'd:/puppeteer',
      headless: false,
      // defaultViewport: { width: 1366, height: 768 }, // 设置默认视口大小
      defaultViewport: { width: 1600, height: 900 }, // 设置默认视口大小
      // defaultViewport: { width: 1920, height: 1080 }, // 设置默认视口大小
    })

    const pages = await browser.pages()
    await pages[0].close() // 关闭初始空白页

    browser.on('disconnected', () => {
      console.log('浏览器已被手动关闭，重新拉起')
      // 在这里执行清理操作或重新启动浏览器
      this.read = false
      this.init()
    })

    this.browser = browser
    this.login()
  }

  async login() {
    const { browser } = this

    const page = await browser.newPage({
      waitUntil: 'networkidle0',
    })

    // 获取屏幕的最大分辨率
    // const dimensions = await page.evaluate(() => {
    //   return {
    //     width: window.screen.width,
    //     height: window.screen.height,
    //   }
    // })

    // 设置视口为屏幕的最大分辨率
    // await page.setViewport({
    //   width: dimensions.width,
    //   height: dimensions.height,
    // })

    await page.goto('https://www.doubao.com/chat/')

    this.page = page
  }

  // 上传文件
  async upload() {
    console.log('upload')

    const { ctx } = this
    const { page } = this

    await page.click('.bp5-overflow-list button')

    await sleep(1000)

    const div = await page.locator('//*[@id="2tsprpz"]/div/div/div/div/div[9]')
    console.log('div', div)
    // 检查元素是否可见
    console.log('找到目标 div')
    await div.click() // 点击元素

    // await page.waitForSelector('.upload_file_panel_upload_item')
    // await page.click('.upload_file_panel_upload_item')

    console.log('获取到按钮')

    // 点击触发文件选择框的按钮
    // await page.waitForSelector('input[type="file"]') // 等待文件输入框出现

    // await fileInput.uploadFile('D:\\test.txt')
  }
}

// 延迟
const sleep = async time => new Promise(resolve => setTimeout(resolve, time))
